#!/usr/bin/env python
#coding=utf-8
import os
import logging

from pyftpdlib.handlers import FTPHandler, ThrottledDTPHandler
from pyftpdlib.servers import ThreadedFTPServer
# from pyftpdlib.filesystems import UnixFilesystem
from pyftpdlib.authorizers import DummyAuthorizer
# from pyftpdlib.servers import FTPServer
# from pyftpdlib.servers import MultiprocessFTPServer

# Instantiate a dummy authorizer for managing 'virtual' users
authorizer = DummyAuthorizer()
# authorizer = UnixAuthorizer(rejected_users=["root"], require_valid_shell=True)

# Define a new user having full r/w permissions and a read-only
authorizer.add_user('admin', 'admin', '.', perm='elradfmwM')
authorizer.add_anonymous(os.getcwd())

# define dtp class
dtp_handler = ThrottledDTPHandler
dtp_handler.read_limit = 30720  # 30 Kb/sec (30 * 1024)
dtp_handler.write_limit = 30720  # 30 Kb/sec (30 * 1024)

# Instantiate FTP handler class
handler = FTPHandler
handler.authorizer = authorizer
# have the ftp handler use the alternative dtp handler class
handler.dtp_handler = dtp_handler
# handler.abstracted_fs = UnixFilesystem

# define log path and log level
logging.basicConfig(filename='/tmp/pyftpd.log', level=logging.INFO)
# Define a customized banner (string returned when client connects)
handler.banner = "pyftpdlib based ftpd ready."
# custom log format
handler.log_prefix = '--- [%(username)s]@%(remote_ip)s'

# Instantiate FTP server class and listen on 0.0.0.0:2121, default listen 0.0.0.0
# server = FTPServer(('127.0.0.1', 2121), handler)
server = ThreadedFTPServer(('127.0.0.1', 2121), handler)

# set a limit for connections
server.max_cons = 256
server.max_cons_per_ip = 5

# start ftp server
server.serve_forever()
